package com.web.webstart.base.security;

import com.alibaba.fastjson.JSON;
import com.web.webstart.base.util.result.XaResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * @ClassName: XaRememberLastUsernameAuthenticationFailureHandler
 * @Description:
 * @author dazer
 * @date 2017/3/13 上午12:22
 */
public class XaRememberLastUsernameAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        HttpSession session = request.getSession();
        session.setAttribute(
                XaSecurityConstants.SECURITY_LAST_USERNAME,
                request.getParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY));


        Integer failureCount = (Integer) session
                .getAttribute("SECURITY_FAILURE_COUNT");

        if (failureCount == null) {
            failureCount = 0;
        }

        failureCount++;

        Boolean captchaSessionToken = false;
        if (failureCount > 3) {
            session.removeAttribute("SECURITY_FAILURE_COUNT");
            session.setAttribute("captchaSessionToken", true);
            captchaSessionToken = true;
        } else {
            session.setAttribute("SECURITY_FAILURE_COUNT", failureCount);
        }

        // rentongtong dazer 支持登录json接口形式 2017.02.16 begin
        if (request.getParameter("datatype") != null && request.getParameter("datatype").equals("json")) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");

            XaResult rs = new XaResult();
            rs.setObject(captchaSessionToken);
            rs.error("用户名或者密码错误！");
            String json = JSON.toJSONString(rs);

            response.getWriter().println(json);
            response.getWriter().flush();
            return;
        }
        // rentongtong dazer 支持登录json接口形式 2017.02.16 end

        super.onAuthenticationFailure(request, response, exception);
    }

}
